#include "widget.h"
#include "ui_widget.h"

#include<QMessageBox>
#include<QDebug>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("客户端");
    socket=new QTcpSocket(this);
    //与服务器建立连接connectToHost
    socket->connectToHost("127.0.0.1",8081);
    //等待或者确认服务器连接是否出错waitForConnect
    bool ret=socket->waitForConnected(2000);
    qDebug()<<ret;
    if(!ret)
    {
        QMessageBox::critical(this,"等待或者连接错误",nullptr,socket->errorString());
        return;
    }
    //通过信号槽，去处理收到的服务器的响应
    connect(socket,&QTcpSocket::readyRead,this,[=](){
        QString response=socket->readAll();
        qDebug()<<response;
        ui->listWidget->addItem("服务端说："+response);
    });
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_clicked()
{
    //获取输入框内容
    QString text=ui->lineEdit->text();
    //清空输入框内容
    ui->lineEdit->setText("");
    //把消息显示到显示器中
    ui->listWidget->addItem("客户端说: "+text);
    //把消息显示到服务器中
    socket->write(text.toUtf8());
}
